//
//  StatusCellPictureView.swift
//  weibo
//
//  Created by 吴婷婷 on 15/11/10.
//  Copyright © 2015年 wutingting. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit

//可重用id
private let StatusPictureCellId = "StatusPictureCellId"

/// 照片之间的间距
private let StatusPictureViewItemMargin: CGFloat = 8

class StatusCellPictureView: UICollectionView{
    ///微博视图模型
    var viewModel: StatusVewModel? {
        didSet {
            sizeToFit()
            
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    //MARK: - 构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = StatusPictureViewItemMargin
        layout.minimumLineSpacing = StatusPictureViewItemMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        registerClass(StatusCellPictureViewCell.self, forCellWithReuseIdentifier: "StatusPictureCellId")
        //设置数据源
        dataSource = self
        //设置代理
        delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

//MARK: - 数据源方法,代理方法
extension StatusCellPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnail?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureCellId, forIndexPath: indexPath) as! StatusCellPictureViewCell
        
//        cell.backgroundColor = UIColor.redColor()
        cell.imageUrl = viewModel?.thumbnail![indexPath.item]
        
        return cell
    }
    //选中缩略图
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
//        photoBrowserFromRect(indexPath)
//        photoBrowserToRect(indexPath)
        let userInfo = [WBStatusSelectedPhotoURLKey: viewModel!.thumbnail!, WBStatusSelectedPhotoIndexPathKey: indexPath]
        //发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(WBStatusSelectedPhotoNotification, object: self, userInfo: userInfo)

    }
}
//MARK: - PhotoBrowserPresentDelegate
extension StatusCellPictureView: PhotoBrowserPresentDelegate {
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        let iv = UIImageView()
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        if let url = viewModel?.thumbnail?[indexPath.item] {
            iv.sd_setImageWithURL(url)
        }
        
        return iv
    }
    func photoBrowserFromRect(indexPath: NSIndexPath) -> CGRect {
        let cell = cellForItemAtIndexPath(indexPath)!
        let rect = convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
//        let v = imageViewForPresent(indexPath)
//        v.frame = rect
//        UIApplication.sharedApplication().keyWindow?.addSubview(v)
        
        return rect
    }
    func photoBrowserToRect(indexPath: NSIndexPath) -> CGRect {
        guard let key = viewModel?.thumbnail?[indexPath.item].absoluteString else {
            return CGRectZero
        }
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else {
            return CGRectZero
        }
        
        let w = UIScreen.mainScreen().bounds.width
        let h = image.size.height * w / image.size.width
        
        let screenHeight = UIScreen.mainScreen().bounds.height
        var y: CGFloat = 0
        if h < screenHeight {
            y = (screenHeight - h) * 0.5
        }
        let rect = CGRectMake(0, y, w, h)
        
//        let v = imageViewForPresent(indexPath)
//        v.frame = rect
//        UIApplication.sharedApplication().keyWindow?.addSubview(v)
        
        return rect
    }
}

//MARK: - 计算视图大小
extension StatusCellPictureView {
    private func calcViewSize() -> CGSize {
        let rowCount: CGFloat = 3
        
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
        let itemWidth = (maxWidth - 2 * StatusPictureViewItemMargin) / rowCount - 0.01
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        let Imgcount = viewModel?.thumbnail?.count ?? 0
        
        if Imgcount == 0 {
            return CGSizeZero
        }
        if Imgcount == 1 {
            var size = CGSizeMake(150, 120)
            //缓存本地图片
            if let key = viewModel?.thumbnail?.first?.absoluteString {
             
                size = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key).size
            }
            //过宽过窄处理
            size.width = size.width < 40 ? 40: size.width
            
            if size.width > 300 {
                let w: CGFloat = 300
                let h: CGFloat = 300 / size.width * size.height
                size = CGSizeMake(w, h)
            }
            
            layout.itemSize = size
            return size
        }
        if Imgcount == 4 {
            
            let w = 2 * itemWidth + StatusPictureViewItemMargin
            return CGSizeMake(w, w)
        }
        
        let row = CGFloat((Imgcount - 1)/Int(rowCount) + 1)
        let h = row * itemWidth + (row - 1) * StatusPictureViewItemMargin
        let w = rowCount * itemWidth + (rowCount - 1) * StatusPictureViewItemMargin
        
        return CGSizeMake(w, h)
        
    }
}

/// 微博配图 Cell
private class StatusCellPictureViewCell: UICollectionViewCell {
    var imageUrl: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageUrl, placeholderImage: nil,
                options: [SDWebImageOptions.RefreshCached, SDWebImageOptions.RetryFailed])
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(iconView)
        
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载控件
    private lazy var iconView: UIImageView = {
       let iv = UIImageView()
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true

        return iv
    }()
    
}










